package com.highstockings.controller;

import com.github.pagehelper.PageInfo;
import com.highstockings.dao.ArticleMapper;
import com.highstockings.dao.ModelMapper;
import com.highstockings.dao.UserMapper;
import com.highstockings.model.Article;
import com.highstockings.model.ArticleDetailsVo;
import com.highstockings.model.Model;
import com.highstockings.model.ModelVo;
import com.highstockings.service.ArticleService;
import com.highstockings.service.GalleryTypeService;
import com.highstockings.service.ModelService;
import com.highstockings.utils.FileUtil;
import com.highstockings.utils.ImageUtil;
import com.highstockings.utils.QiniuUtil;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 文章管理业务逻辑
 * Created by diablo13064 on 2018/3/26.
 */
@Controller
@RequestMapping("/article")
public class ArticleController {
    //private static String dir = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"/static/upload/";


    //private LinkedHashMap<String, String> map = null;                                                                  //本地文件与骑牛链接的映射
    @Autowired
    ArticleService articleService;

    @Autowired
    ModelService modelService;
    @Autowired
    GalleryTypeService galleryTypeService;

    @Autowired
    QiniuUtil qiniuUtil;
    @Autowired
    ImageUtil imageUtil;

    @Autowired
    ArticleMapper articleMapper;

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    UserMapper userMapper;

    @RequestMapping("/test")
    public String  test() throws UnsupportedEncodingException {
        /*List<ArticleDetailsVo> list = articleMapper.selectArticleByCondition("tag");*/
        //List<ArticleDetailsVo> list = articleMapper.selectArticleByModelId(2);
        List<ArticleDetailsVo> articleDetailsVo = articleMapper.selectArticleHome();
        //articleDetailsVo.setStars(5.0f);
        return "admin/test";
    }

    /**
     * 主页
     *
     * @param request
     * @return
     */
    @RequestMapping("/home")
    public String homePage(HttpServletRequest request, @RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum,
                           @RequestParam(value = "pageSize", required = false, defaultValue = "20") int pageSize, ModelMap modelMap) {
        modelMap.addAttribute("pageName", "欢迎来到丝图诱惑!");
        List<ArticleDetailsVo> list = articleService.findArticleHome(pageNum, pageSize);
        modelMap.addAttribute("articleHome", list);
        modelMap.addAttribute("pageHome", new PageInfo<>(list));
        return "home";
    }


    /**
     * 国产欧美套图/视频
     * * @return
     */
    @RequestMapping("/gallerytype")
    public String articleFromForeign(String type, @RequestParam(value = "pageNum",required = false,defaultValue = "1")int pageNum,
                                     @RequestParam(value = "pageSize", required = false, defaultValue = "6") int pageSize, ModelMap modelMap, HttpSession session) {
        List<ArticleDetailsVo> list = new ArrayList<>();
        if (type == null) {
            type = (String) session.getAttribute("type");
        }
        switch (type) {
            case "china":
                modelMap.addAttribute("pageName", "国内嫩模套图");
                list = articleService.findArticleByCountry("中国", pageNum, pageSize);
                break;
            case "foreign":
                modelMap.addAttribute("pageName", "国外模特套图");
                list = articleService.findArticleByCountry("外国", pageNum, pageSize);
                //modelMap.addAttribute("foreignArticle",list);
                break;
            case "video":
                modelMap.addAttribute("pageName", "性感诱惑视频");
                break;
        }
        if (type != null) {
            session.setAttribute("type", type);
        }
        modelMap.addAttribute("articleList", list);
        PageInfo pageInfo = new PageInfo(list);
        modelMap.addAttribute("pageInfo", pageInfo);

        return "showup/gallery_type";
    }
    /**
     * 查看文章
     * * @param aid
     * @param modelMap
     * @return
     */
    @RequestMapping("/view/{aid}")
    public String viewArticle(@PathVariable("aid") int aid, ModelMap modelMap) {
        ArticleDetailsVo articleDetailsVo = articleService.findArticleDeitalsById(aid);

        if (articleDetailsVo != null) {
            modelMap.addAttribute("articleDetails", articleDetailsVo);
            modelMap.addAttribute("pageName", articleDetailsVo.getTitle());
            articleService.addViewCount(aid);
        } else {
            return "admin/partner/404";
        }
        return "showup/pic_details";
    }

    /**
     * 模特列表
     *
     * @param pageNum
     * @param pageSize
     * @param modelMap
     * @return
     */
    @RequestMapping("/modelList")
    public String modelList(@RequestParam(value = "pageNum",required = false,defaultValue = "1")int pageNum,
                            @RequestParam(value = "pageSize", required = false, defaultValue = "6") int pageSize, ModelMap modelMap){

        List<ModelVo> modelVos = modelService.findAllModelVo(pageNum, pageSize);
        PageInfo pageInfo = new PageInfo(modelVos);
        modelMap.addAttribute("modelList", modelVos);
        modelMap.addAttribute("pageInfo", pageInfo);
        modelMap.addAttribute("nullModelInfo", modelService.findModelById(0));
        modelMap.addAttribute("recentModelInfo", modelService.findRecentModelVo());
        return "showup/model_list";
    }

    @RequestMapping("/addModel")
    public String addModel(Model model, String birthdate, MultipartFile file, ModelMap modelMap) throws Exception {
        model.setBirthday(FileUtil.String2Date(birthdate, "yyyy-MM-dd"));
        if (model.getMeasurements().contains("-") || !model.getMeasurements().contains("B") || !model.getMeasurements().contains("W")) {
            String[] strings = model.getMeasurements().split("-");
            /*B90 W65 H91*/
            String s = "B" + strings[0] + " " + "W" + strings[1] + " " + "H" + strings[2];
            model.setMeasurements(s);
        }

        String temp_dir = articleService.getUploadDir();
        File temp_fileName = new File(temp_dir + "model_" + model.getAlias() + ".jpg");
        if (!temp_fileName.exists()) {
            temp_fileName.createNewFile();
        }
        File f = new File(temp_dir + file.getOriginalFilename());
        f.createNewFile();                                                          //创建临时文件
        file.transferTo(f);                                                         //MultipartFile 转File
        ImageUtil.zoomBySize(f, temp_fileName, 700, 480);                                         //图片压缩
        f.delete();                                                                 //临时文件删除
        qiniuUtil.upload(FileUtil.File2byte(temp_fileName.getAbsolutePath()), temp_fileName.getName());
        model.setPiclink(qiniuUtil.getSecretDownLink(temp_fileName.getName()));
        modelService.addModelAlias(model);
        return "redirect:/admin/mmodel";
    }

    /**
     * 关键字查询（模糊查询，信息检索）
     * @param info
     * @param modelMap
     * @return
     */
    @RequestMapping("/search")
    public String searchArticle(String info, @RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum,
                                @RequestParam(value = "pageSize", required = false, defaultValue = "6") int pageSize, ModelMap modelMap) {

        List<ArticleDetailsVo> list = articleService.findArticleByTag(info, pageNum, pageSize);
        if (list.size() > 0) {
            modelMap.addAttribute("articleList", list);
            PageInfo pageInfo = new PageInfo(list);
            modelMap.addAttribute("pageInfo", pageInfo);
            modelMap.addAttribute("pageName", "检索结果：" + list.size() + "条");
        } else {
            return "redirect:/article/gallerytype?type='中国'";
        }
        return "showup/gallery_type";
    }

    /**
     * 详细信息
     * @param mid
     * @param modelMap
     * @return
     */
    @RequestMapping("/model_details")
    public String modelDetails(@RequestParam(required = false) Integer mid,
                               @RequestParam(value = "pageNum",required = false,defaultValue = "1")int pageNum,
                               @RequestParam(value = "pageSize",required = false,defaultValue = "6")int pageSize,
                               ModelMap modelMap) {
        Model model = modelService.findModelById(mid);
        if (model != null) {
            //模特资料
            modelService.upModelBuzz(mid);
            modelMap.addAttribute("modelDetails", model);
            modelMap.addAttribute("pageName", model.getAlias() + "的详细资料");
            //模特标签
            List<String> taglist = new ArrayList<>();
            taglist.add(model.getModellabel());
            modelMap.addAttribute("tagList", FileUtil.tagSeperators(taglist));
            //模特所拥有的套图目录

            List<ArticleDetailsVo> list = articleService.findArticleByModelId(model.getMid(),pageNum,pageSize);
            modelMap.addAttribute("articleAboutModel", list);
        } else {
            return "";
        }
        return "showup/model_details";
    }

    /**
     * 删除文章
     *
     * @param aid
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String deleteArticle(@RequestParam("aid") Integer aid, ModelMap modelMap) {
        modelMap.addAttribute("pageName", "删除文章");
        if (articleMapper.deleteByPrimaryKey(aid) > 0) {
            return "删除成功！";
        }
        return "删除失败！";
    }

    /**
     * 信息更新
     * @param article
     * @return
     */
    @RequestMapping("/update")
    @ResponseBody
    public String updateArticle(Article article) throws InvocationTargetException, IllegalAccessException {
        int statusCode = articleMapper.updateByPrimaryKeySelective(article);
        if (statusCode != 0) {
            return "更新成功！";
        }
        return "更新失败！";
    }

    /**
     * 改变文章状态
     *
     * @return
     */
    @RequestMapping("/change")
    @ResponseBody
    public String changeArticle(int aid, String status) {
        ArticleDetailsVo articleDetailsVo = articleService.findArticleDeitalsById(aid);
        Map<String, String> map = new HashMap<>();
        if (articleDetailsVo != null) {
            if (status.contains("on")) {
                articleService.changeState("ON", aid);
                return "状态修改:ON";
            } else if (status.contains("off")) {
                articleService.changeState("OFF", aid);
                return "状态修改:OFF";
            }
        } else {
            return "状态修改失败";
        }
        return "";
    }
    @RequestMapping(value = "/upload")
    public @ResponseBody String uploadFile(@RequestParam("file")MultipartFile[] files, HttpServletRequest request) throws Exception {
        File upload_dir = new File(articleService.getUploadDir());
        if (!(upload_dir.exists())) {
            upload_dir.mkdirs();
        }
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(Calendar.getInstance().getTime());
        MultipartFile file = files[0];
        File temp_file = null;
        if (file.getOriginalFilename().contains("cover")) {
            temp_file = new File(upload_dir + File.separator + timestamp + "_" + file.getOriginalFilename());
        } else {
            temp_file = new File(upload_dir + File.separator+timestamp + ".jpg");

        }
        if (!temp_file.exists()) {
            temp_file.createNewFile();
        }
        File f = new File(upload_dir + File.separator + file.getOriginalFilename());
        f.createNewFile();                                                          //创建临时文件
        file.transferTo(f);                                                         //MultipartFile 转File
        ImageUtil.zoomBySize(f, temp_file);                                         //图片压缩
        f.delete();                                                                 //临时文件删除
        //InputStream is = file.getInputStream();
        //BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(temp_file));
        //FileCopyUtils.copy(is, bos);
        return "success";
    }

    //提交文章,提交时在上传到七牛云
    @RequestMapping(value = "/commit", method = RequestMethod.POST)
    public String commitArticle(@ModelAttribute Article article) throws Exception {
        articleService.addArticle(article);
        return "redirect:/admin/mcontent";
    }


    /**
     * 联系我们
     *
     * @return
     */
    @RequestMapping("/contact")
    public String contact() {
        return "showup/contact";
    }

    /**
     * 关于我们&免责声明
     *
     * @return
     */
    @RequestMapping("/about")
    public String aboutUs() {
        return "showup/about";
    }
}
